
const nums = [-1, 0, 3, 5, 9, 12], target = 4;

// 循环解法
var search1 = function (nums, target) {
  let index = -1;
  nums.forEach((e, i) => {
    if (e === target) {
      index = i;
      return
    }
  });
  return index;
};
// 二分查找 在数组有序的情况下
var search = function (nums, target) {
  let left = 0;
  let right = nums.length - 1;
  while (left <= right) {
    const mid = Math.floor((right + left) / 2);
    const e = nums[mid];
    if (target === e) {
      return mid;
    }
    debugger
    // 如果小于中数
    if (target < e) {
      right = mid - 1;
    }
    // 大于中数
    if (target > e) {
      left = mid + 1;
    }
  }
  return -1;
};


console.log(search(nums, target));